import 'package:blurb/common/models/comment.dart';
import 'package:blurb/common/routers/names.dart';
import 'package:blurb/common/services/comment_service.dart';
import 'package:blurb/common/values/images.dart';
import 'package:blurb/common/values/svg.dart';
import 'package:blurb/pages/community/sharing_publish.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:blurb/common/store/user_store.dart';
import 'package:blurb/common/store/share_store.dart';
import 'package:blurb/common/models/share.dart';
import 'package:blurb/common/models/user.dart';
import 'package:blurb/common/services/user_service.dart';
import 'package:flutter_mobx/flutter_mobx.dart';

class CommunityPage extends StatefulWidget {
  const CommunityPage({super.key});

  @override
  State<CommunityPage> createState() => _CommunityPageState();
}

class _CommunityPageState extends State<CommunityPage> {
  bool _isLoading = false;
  List<Share> _otherUsersShares = [];
  int? _previousUserId; // 用于跟踪用户ID变化

  @override
  void initState() {
    super.initState();
    _loadShares();
  }

  Future<void> _loadShares() async {
    final userStore = Provider.of<UserStore>(context, listen: false);
    final shareStore = Provider.of<ShareStore>(context, listen: false);
    
    setState(() {
      _isLoading = true;
    });
    
    try {
      await shareStore.refreshShares();
      
      // 获取当前用户ID
      final currentUserId = userStore.currentUser?.id;
      _previousUserId = currentUserId; // 更新前一个用户ID
      
      if (currentUserId != null) {
        // 已登录：显示除当前用户外的其他用户分享
        _otherUsersShares = shareStore.shares
            .where((share) => share.userId != currentUserId)
            .toList();
      } else {
        // 未登录：显示所有分享
        _otherUsersShares = shareStore.shares;
      }
      
      // 按时间排序，最新的在前面
      _otherUsersShares.sort((a, b) => 
          DateTime.parse(b.time).compareTo(DateTime.parse(a.time)));
      
      // 如果有多个分享，只保留最新的一个用于显示
      if (_otherUsersShares.length > 1) {
        _otherUsersShares = [_otherUsersShares.first];
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景图片固定在底部
          Positioned.fill(
            child: Image.asset(MIP.background, fit: BoxFit.cover),
          ),
          // 内容部分
          Observer(
            builder: (_) {
              // 监听用户登录状态变化
              final userStore = Provider.of<UserStore>(context);
              final currentUserId = userStore.currentUser?.id;
              
              // 当用户登录状态变化时，重新加载分享
              if (_previousUserId != currentUserId) {
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  _loadShares();
                });
              }
              
              return SingleChildScrollView(
                child: SafeArea(
                  child: Column(
                    children: [
                      // 标题
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              'Topic Discussion',
                              style: GoogleFonts.racingSansOne(
                                fontSize: 24.sp,
                                fontWeight: FontWeight.normal,
                                color: Colors.white,
                              ),
                            ),
                            Icon(
                              Icons.video_camera_back,
                              color: Colors.white,
                              size: 28.sp,
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 20.h),

                      // 话题列表
                      Stack(
                        children: [
                          Container(
                            width: double.infinity,
                            height: 249.h,
                            decoration: BoxDecoration(color: Colors.transparent),
                            child: Image.asset(MIP.topicsBackground),
                          ),
                          Positioned(
                            top: 2.h,
                            right: 35.w,
                            child: GestureDetector(
                              onTap: () {
                                GoRouter.of(context).push(RNS.topic);
                              },
                              child: Text(
                                'All discussions',
                                style: GoogleFonts.racingSansOne(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.normal,
                                  color: Colors.white.withOpacity(0.8),
                                ),
                              ),
                            ),
                          ),
                          Positioned(
                            top: 10.h,
                            left: 30.w,
                            child: Container(
                              width: 185.w,
                              height: 225.h,
                              child: Image.asset(MIP.dailyTopicsBackground),
                            ),
                          ),
                          Positioned(
                            top: 48.h,
                            right: 30.w,
                            child: Container(
                              width: 155.w,
                              height: 192.h,
                              child: Image.asset(MIP.hotTopicsBackground),
                            ),
                          ),
                          Positioned(
                            top: 55.h,
                            left: 42.w,
                            child: Container(
                              width: 161.w,
                              height: 84.h,
                              child: Image.asset(MIP.dailyTopics1),
                            ),
                          ),
                          Positioned(
                            bottom: 21.h,
                            left: 42.w,
                            child: Container(
                              width: 161.w,
                              height: 84.h,
                              child: Image.asset(MIP.dailyTopics2),
                            ),
                          ),
                          Positioned(
                            bottom: 21.h,
                            right: 42.w,
                            child: Container(
                              width: 131.w,
                              height: 143.h,
                              child: Image.asset(MIP.hotTopics),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 20.h),
                      // 小组聊天
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Row(
                          children: [
                            Text(
                              'Sunscreen Group Chat',
                              style: GoogleFonts.racingSansOne(
                                fontSize: 24.sp,
                                fontWeight: FontWeight.normal,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 10.h),
                      Container(
                        height: 80.h,
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: 3,
                          itemBuilder: (context, index) {
                            return Container(
                              margin: EdgeInsets.only(right: 10.w),
                              decoration: BoxDecoration(
                                color: const Color(0xFF1F1F21),
                                borderRadius: BorderRadius.circular(10.r),
                                border: Border.all(
                                  color: Colors.white.withOpacity(0.1),
                                ),
                              ),
                              padding: EdgeInsets.symmetric(
                                horizontal: 16.w,
                                vertical: 10.h,
                              ),
                              child: Row(
                                children: [
                                  Stack(
                                    children: [
                                      // 设置一个占位容器，确保Stack有足够的尺寸
                                      Container(
                                        width: 70.w,
                                        height: 60.h,
                                        color: Colors.transparent,
                                      ),
                                      // 居中放置添加图标
                                      Positioned.fill(
                                        child: Center(
                                          child: Icon(
                                            Icons.add,
                                            size: 22.sp,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                      // 左上角图片
                                      Positioned(
                                        top: 0,
                                        left: 0,
                                        child: Image.asset(
                                          MIP.empty,
                                          width: 28.w,
                                          height: 28.h,
                                        ),
                                      ),
                                      // 右上角图片
                                      Positioned(
                                        top: 0,
                                        right: 0,
                                        child: Image.asset(
                                          MIP.empty,
                                          width: 28.w,
                                          height: 28.h,
                                        ),
                                      ),
                                      // 左下角图片
                                      Positioned(
                                        bottom: 0,
                                        left: 0,
                                        child: Image.asset(
                                          MIP.empty,
                                          width: 28.w,
                                          height: 28.h,
                                        ),
                                      ),
                                      // 右下角图片
                                      Positioned(
                                        bottom: 0,
                                        right: 0,
                                        child: Image.asset(
                                          MIP.empty,
                                          width: 28.w,
                                          height: 28.h,
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(width: 10.w),
                                  Text(
                                    'Sun-proof Research\nInstitute',
                                    style: GoogleFonts.inter(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.normal,
                                      color: Colors.white,
                                    ),
                                  ),
                                  SizedBox(width: 20.w),
                                  Container(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 10.w,
                                      vertical: 5.h,
                                    ),
                                    decoration: BoxDecoration(
                                      gradient: LinearGradient(
                                        begin: Alignment(0.50, 0.00),
                                        end: Alignment(0.50, 0.96),
                                        colors: [
                                          const Color(0xFF60C3FF),
                                          const Color(0xFFAADEFC),
                                        ],
                                      ),
                                      borderRadius: BorderRadius.circular(37.r),
                                    ),
                                    child: Text(
                                      'Join in',
                                      style: GoogleFonts.racingSansOne(
                                        fontSize: 18.sp,
                                        fontWeight: FontWeight.normal,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                      ),
                      SizedBox(height: 20.h),
                      // 防晒分享
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              'Sunscreen Goodies Sharing',
                              style: GoogleFonts.racingSansOne(
                                fontSize: 22.sp,
                                fontWeight: FontWeight.normal,
                                color: Colors.white,
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                GoRouter.of(context).push(RNS.sharing);
                              },
                              child: Text(
                                'View All',
                                style: GoogleFonts.racingSansOne(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.normal,
                                  color: Colors.white,
                                  decoration: TextDecoration.underline,
                                  decorationColor: Colors.white,
                                  decorationThickness: 1,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 10.h),
                      _isLoading
                      ? Center(
                          child: Container(
                            height: 100.h,
                            child: CircularProgressIndicator(
                              color: Color(0xFF60C3FF),
                            ),
                          ),
                        )
                      : _otherUsersShares.isEmpty
                        ? Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 15.w,
                              vertical: 20.h,
                            ),
                            margin: EdgeInsets.symmetric(horizontal: 16.w),
                            decoration: BoxDecoration(
                              color: const Color(0xFF1F1F21),
                              borderRadius: BorderRadius.circular(19.r),
                              border: Border.all(color: Colors.white.withOpacity(0.1)),
                            ),
                            child: Center(
                              child: Text(
                                'No sharing content',
                                style: GoogleFonts.inter(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.normal,
                                  color: Colors.white70,
                                ),
                              ),
                            ),
                          )
                        : _buildShareItem(_otherUsersShares.first),
                      // 底部留白
                      SizedBox(height: 70.h),
                    ],
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
  
  Widget _buildShareItem(Share share) {
    return FutureBuilder<User?>(
      future: UserService.getUserById(share.userId),
      builder: (context, snapshot) {
        final String userName = snapshot.hasData && snapshot.data != null 
            ? snapshot.data!.nickname 
            : 'User ${share.userId}';
        final String userAvatar = snapshot.hasData && snapshot.data != null 
            ? snapshot.data!.avatar 
            : MIP.avatar;
            
        // 格式化时间
        final DateTime shareTime = DateTime.parse(share.time);
        final String formattedTime = _formatShareTime(shareTime);
        
        return GestureDetector(
          onTap: () {
            GoRouter.of(context).push('/community/sharing/detail?id=${share.id}');
          },
          child: 
        Container(
          padding: EdgeInsets.symmetric(
            horizontal: 15.w,
            vertical: 10.h,
          ),
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          decoration: BoxDecoration(
            color: const Color(0xFF1F1F21),
            borderRadius: BorderRadius.circular(19.r),
            border: Border.all(color: Colors.white.withOpacity(0.1)),
          ),
          child: Column(
            children: [
              Row(
                children: [
                  Container(
                    width: 48.w,
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: const Color(0xFF60C3FF).withOpacity(0.7),
                        width: 1.5.w,
                      ),
                    ),
                    child: ClipOval(
                      child: Image.asset(userAvatar, fit: BoxFit.cover),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    userName,
                    style: GoogleFonts.racingSansOne(
                      fontSize: 24.sp,
                      fontWeight: FontWeight.normal,
                      color: Colors.white,
                    ),
                  ),
                  SizedBox(width: 10.w),
                  Text(
                    formattedTime,
                    style: GoogleFonts.inter(
                      fontSize: 12.sp,
                      fontWeight: FontWeight.normal,
                      color: Colors.white,
                    ),
                  ),
                  Spacer(),
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 12.w,
                      vertical: 6.h,
                    ),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.50, 0.00),
                        end: Alignment(0.50, 0.96),
                        colors: [
                          const Color(0xFF60C3FF),
                          const Color(0xFFAADEFC),
                        ],
                      ),
                      borderRadius: BorderRadius.circular(37.r),
                    ),
                    child: Row(
                      children: [
                        Container(
                          width: 16.w,
                          height: 16.h,
                          decoration: BoxDecoration(
                            color: Colors.transparent,
                            borderRadius: BorderRadius.circular(12.r),
                            border: Border.all(
                              color: Colors.white,
                              width: 1.w,
                            ),
                          ),
                          child: Icon(
                            Icons.favorite_border,
                            color: Colors.white,
                            size: 12.sp,
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          'Follow',
                          style: GoogleFonts.inter(
                            fontSize: 12.sp,
                            fontWeight: FontWeight.normal,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 10.h),
              Text(
                share.description,
                style: GoogleFonts.inter(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.normal,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 10.h),
              _buildShareImages(share),
              SizedBox(height: 8.h),
              Row(
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 12.w,
                      vertical: 6.h,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.transparent,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Icon(
                          MSI.collection,
                          color: Colors.white,
                          size: 24.sp,
                        ),
                        SizedBox(width: 6.w),
                        Text(
                          '13',
                          style: GoogleFonts.inter(
                            fontSize: 12.sp,
                            fontWeight: FontWeight.normal,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: 4.w),
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 12.w,
                      vertical: 6.h,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.transparent,
                    ),
                    child: FutureBuilder<List<Comment>>(
                      future: CommentService.getShareComments(share.id),
                      builder: (context, snapshot) {
                        int commentCount = 0;
                        if (snapshot.hasData) {
                          commentCount = snapshot.data!.length;
                        }
                        return 
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                        Icon(
                          MSI.comment,
                          color: Colors.white,
                          size: 24.sp,
                        ),
                        SizedBox(width: 6.w),
                        Text(
                          '$commentCount',
                          style: GoogleFonts.inter(
                            fontSize: 12.sp,
                            fontWeight: FontWeight.normal,
                            color: Colors.white,
                          ),
                        ),
                          ],
                        );
                      },
                    ),
                  ),
                  Spacer(),
                  Icon(MSI.report, color: Colors.white, size: 24.sp),
                ],
              ),
            ],
          ),
        ));
      },
    );
  }

  Widget _buildShareImages(Share share) {
    // 检查是否有发布的图片数据
    final bool hasPublishedImages = SharingPublishPage.publishedImages.containsKey(share.id);
    
    // 确定要显示的图片数量
    final int imageCount = hasPublishedImages 
        ? SharingPublishPage.publishedImages[share.id]!.length 
        : share.pictures.length;
    
    if (imageCount == 0) {
      return const SizedBox.shrink();
    } else if (imageCount == 1) {
      // 单张图片，显示大图
      return ClipRRect(
        borderRadius: BorderRadius.circular(12.r),
        child: hasPublishedImages
            ? Image.memory(
                SharingPublishPage.publishedImages[share.id]![0],
                fit: BoxFit.cover,
                width: double.infinity,
                height: 200.h,
              )
            : Image.asset(
                share.pictures[0],
                fit: BoxFit.cover,
                width: double.infinity,
                height: 200.h,
              ),
      );
    } else {
      // 多张图片，显示网格
      return Row(
        children: List.generate(imageCount, (index) {
          return Expanded(
            child: Padding(
              padding: EdgeInsets.only(right: index < imageCount - 1 ? 8.w : 0),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12.r),
                child: hasPublishedImages
                    ? Image.memory(
                        SharingPublishPage.publishedImages[share.id]![index],
                        fit: BoxFit.cover,
                        height: 150.h,
                      )
                    : Image.asset(
                        share.pictures[index],
                        fit: BoxFit.cover,
                        height: 150.h,
                      ),
              ),
            ),
          );
        }),
      );
    }
  }
  
  String _formatShareTime(DateTime shareTime) {
    final DateTime now = DateTime.now();
    final Duration difference = now.difference(shareTime);

    if (difference.inDays > 365) {
      return '${(difference.inDays / 365).floor()} years ago';
    } else if (difference.inDays > 30) {
      return '${(difference.inDays / 30).floor()} months ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }
}